package cn.com.xky.jdbctemplate.dao.impl;

import cn.com.xky.jdbctemplate.dao.IUserDao;
import cn.com.xky.jdbctemplate.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by EKEYXIA on 2017/8/11.
 */
@Repository
public class UserDaoImp implements IUserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(User user) {
        jdbcTemplate.update("INSERT INTO demo.test(NAME,AGE) VALUES (?, ?)",user.getName(),user.getAge());
    }

    @Override
    public void delete(Integer id) {
        jdbcTemplate.update("DELETE FROM demo.test where id = ?", id);
    }


    @Override
    public void update(Integer id, User user) {
        jdbcTemplate.update("update demo.test set NAME = "+user.getName()+" , age = "+user.getAge()+" where id = "+user.getId());
    }

    @Override
    public List<User> getAll() {
        String sql = "select * from demo.test";

        List<User> list = jdbcTemplate.query(sql,new Object[]{},new BeanPropertyRowMapper<>(User.class));
        if (list.size() > 0){
            return list;
        }
        return null;
    }

    @Override
    public User getOne(Integer id) {
        String sql = "select * from demo.test where id = ?";
        List<User> list = jdbcTemplate.query(sql,new Object[]{id},new BeanPropertyRowMapper<>(User.class));
        if (list != null && list.size() > 0){
            return list.get(0);
        }
        return null;
    }
}
